package com.acce.gxsc.common;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.gxsc.model.WorkModel;
import com.acce.gxsc.model.loaclBean.DutyLogBean;
import com.acce.gxsc.model.loaclBean.ResultBean;
import com.acce.gxsc.model.netBean.DutyBean;
import com.acce.sdk.User;
import com.acce.sdk.base.main.Category;
import com.acce.sdk.base.main.OffsetDecoration;
import com.acce.sdk.base.mvp.BaseMvpActivity;
import com.acce.sdk.model.LoginModel;
import com.acce.sdk.model.bean.Version;
import com.acce.sdk.user.PersonInfoActivity;
import com.acce.sdk.user.joinCompany.SearchCompanyActivity;
import com.acce.sdk.user.login.LoginActivity;
import com.acce.sdk.user.modifyPwd.ModifyPwdActivity;
import com.acce.sdk.user.organization.OrganizationActivity;
import com.acce.sdk.user.permManager.widget.PermManagerActivity;
import com.acce.sdk.user.register.RegisterCompanyActivity;
import com.acce.sdk.user.versionupdate.VersionUpdatePresenter;
import com.acce.sdk.user.versionupdate.VersionUpdateView;
import com.acce.sdk.utils.SharePreferencesManager;
import com.acce.sdk.utils.ToastUtils;
import com.acce.sdk.utils.TransitionHelper;
import com.acce.sdk.utils.VolleySingleton;
import com.acce.sdk.widget.AcceBar;
import com.acce.sdk.widget.CircleImageView;
import com.acce.sdk.widget.adapterrv.CommonAdapter;
import com.acce.sdk.widget.adapterrv.ViewHolder;
import com.acce.sdk.widget.lemonAlert.LemonAlert;
import com.acce.sdk.widget.lemonAlert.LemonAlertAction;
import com.acce.sdk.widget.lemonAlert.LemonAlertInfo;
import com.acce.sdk.widget.lemonAlert.LemonAlertView;
import com.acce.sdk.widget.lemonAlert.interfaces.LemonAlertActionDelegate;
import com.android.volley.toolbox.ImageLoader;

import java.text.MessageFormat;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;

import static com.acce.sdk.BaseApp.context;

public class MainActivity extends BaseMvpActivity<VersionUpdateView, VersionUpdatePresenter> implements VersionUpdateView {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.accebar)
    AcceBar accebar;
    @Bind(R.id.navigation_view)
    NavigationView navigationView;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.rv_categories)
    RecyclerView rvCategories;

    private ActionBarDrawerToggle drawerToggle;

    private CircleImageView civHeaderPic;
    private TextView tvCompanyName;
    private TextView tvPosition;
    private TextView tvUserName;

    DutyBean mDutyBean;
    String [] place=new String[]{"A1","A2","B1","B2","C1","C2","D1","D2"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        mDutyBean = (DutyBean) getIntent().getSerializableExtra("duty");
        initLayoutView();
        syncAppVersion(true);
        loadDutyInfo();
        showSelectDialog();
    }

    @Override
    protected VersionUpdatePresenter createPresenter() {
        return new VersionUpdatePresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setupDrawerContent(navigationView);
    }

    private void initLayoutView() {
        if (mDutyBean.gateNo != null) {
            accebar.setCustomizeText(mDutyBean.gateName);
        }
        accebar.setPageCode(mDutyBean.dutyId);
        // 设置ActionBarDrawerToggle
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
        drawerToggle.syncState();
        drawerLayout.addDrawerListener(drawerToggle);

        final int spacing = getResources().getDimensionPixelSize(R.dimen.spacing_nano);
        rvCategories.addItemDecoration(new OffsetDecoration(spacing));
        setAdapterStandard();
        supportPostponeEnterTransition();
    }

    private void setAdapterSimple() {
        //设置内容
        rvCategories.setAdapter(new CommonAdapter<Category>(this, R.layout.item_category_simple, Constants.categoryList) {
            @Override
            protected void convert(final ViewHolder holder, final Category category, final int position) {
                holder.setText(R.id.tv_category_title, category.getName());
                holder.setTextColor(R.id.tv_category_title, getResources().getColor(category.getTheme().getTextPrimaryColor()));
                holder.setBackgroundColor(R.id.rl_category, getResources().getColor(category.getTheme().getPrimaryColor()));
                holder.setOnClickListener(R.id.tv_category_title, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startQuizActivityWithTransition(MainActivity.this, holder.getView(R.id.tv_category_title), position);
                    }
                });
            }
        });

        rvCategories.getViewTreeObserver()
                .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        rvCategories.getViewTreeObserver().removeOnPreDrawListener(this);
                        MainActivity.this.supportStartPostponedEnterTransition();
                        return true;
                    }
                });
    }

    private void setAdapterStandard() {
        //设置内容
        rvCategories.setAdapter(new CommonAdapter<Category>(this, R.layout.item_category, Constants.categoryList) {
            @Override
            protected void convert(final ViewHolder holder, final Category category, final int position) {
                holder.setText(R.id.tv_title, category.getName());
                holder.setTextColor(R.id.tv_title, getResources().getColor(category.getTheme().getTextPrimaryColor()));
                holder.setBackgroundColor(R.id.tv_title, getResources().getColor(category.getTheme().getPrimaryColor()));
                holder.setBackgroundColor(R.id.category_item, getResources().getColor(category.getTheme().getWindowBackgroundColor()));
                holder.setImageResource(R.id.img_category_icon, category.getResId());
                holder.setOnClickListener(R.id.category_item, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startQuizActivityWithTransition(MainActivity.this, holder.getView(R.id.tv_title), position);
                    }
                });
            }
        });

        rvCategories.getViewTreeObserver()
                .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        rvCategories.getViewTreeObserver().removeOnPreDrawListener(this);
                        MainActivity.this.supportStartPostponedEnterTransition();
                        return true;
                    }
                });
    }

    /** 弹出对话框 */
    int index=0;
    private void showSelectDialog(){

        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        AlertDialog dialog=builder.setTitle("请选择区域")
                .setSingleChoiceItems(place, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        index=which;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        App.currentPlace=place[index];
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        Intent intent;
                        switch (menuItem.getItemId()) {
                            /*
                            case R.id.navigation_item_exit:
                                LemonAlert.getInformationAlert("退出登录", "您确定要退出登录吗？")
                                        .addAction(new LemonAlertAction("取消", new LemonAlertActionDelegate() {
                                            @Override
                                            public void onClick(LemonAlertView alertView, LemonAlertInfo alertInfo, LemonAlertAction alertAction) {
                                                alertView.hide();
                                            }
                                        }))
                                        .addAction(new LemonAlertAction("退出登录", Color.RED, new LemonAlertActionDelegate() {
                                            @Override
                                            public void onClick(LemonAlertView alertView, LemonAlertInfo helloInfo, LemonAlertAction helloAction) {
                                                alertView.hide();
                                                LoginModel loginModel = new LoginModel();
                                                loginModel.exitLogin(MainActivity.this);

                                                Intent loginStarter = new Intent(MainActivity.this, LoginActivity.class);
                                                startActivity(loginStarter);
                                                finish();
                                            }
                                        })).show(MainActivity.this);
                                break;*/
                            case R.id.navigation_item_organization:

                                intent = new Intent(MainActivity.this, OrganizationActivity.class);
                                startActivity(intent);
                                break;
                            case R.id.navigation_permission_manager:
                                intent = new Intent(MainActivity.this, PermManagerActivity.class);
                                startActivity(intent);
                                break;
                            case R.id.navigation_item_modify_pwd:
                                intent = new Intent(MainActivity.this, ModifyPwdActivity.class);
                                startActivity(intent);
                                break;
                            case R.id.navigation_item_person_info:
                                intent = new Intent(MainActivity.this, PersonInfoActivity.class);
                                startActivity(intent);
                                break;
                            case R.id.navigation_item_version:
                                showProgressDialog("正在检测新版本...", false);
                                syncAppVersion(false);
                                break;
                            case R.id.navigation_item_out_work:
                                LemonAlert.getInformationAlert("退出登录并下班", "您确定要退出登录并下班吗？")
                                        .addAction(new LemonAlertAction("取消", new LemonAlertActionDelegate() {
                                            @Override
                                            public void onClick(LemonAlertView alertView, LemonAlertInfo alertInfo, LemonAlertAction alertAction) {
                                                alertView.hide();
                                            }
                                        }))
                                        .addAction(new LemonAlertAction("退出登录并下班", Color.RED, new LemonAlertActionDelegate() {
                                            @Override
                                            public void onClick(LemonAlertView alertView, LemonAlertInfo helloInfo, LemonAlertAction helloAction) {
                                                alertView.hide();
                                                exit();
                                            }
                                        })).show(MainActivity.this);
                                break;
                        }
                        return false;
                    }
                });

        //设置headerView上的用户信息
        View headerView = navigationView.getHeaderView(0);
        if (User.getInstance().getCompanyId() != null) {
            civHeaderPic = (CircleImageView) headerView.findViewById(R.id.profile_image);
            if (User.getInstance().getThumbnail() != null) {
                VolleySingleton.getVolleySingleton(this).getImageLoader().get(User.getInstance().getThumbnail(),
                        ImageLoader.getImageListener(civHeaderPic, 0, 0));
            }
            tvCompanyName = (TextView) headerView.findViewById(R.id.tv_company_name);
            tvCompanyName.setText(User.getInstance().getCompanyName());
            tvPosition = (TextView) headerView.findViewById(R.id.tv_position);
            tvPosition.setText(User.getInstance().getDepartmentName());
        } else {
            tvPosition = (TextView) headerView.findViewById(R.id.tv_position);
            tvPosition.setText("点我创建或加入公司");
            tvPosition.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    LemonAlert.getInformationAlert("请选择", "加入公司或创建新公司")
                            .addAction(new LemonAlertAction("创建新公司", new LemonAlertActionDelegate() {
                                @Override
                                public void onClick(LemonAlertView alertView, LemonAlertInfo alertInfo, LemonAlertAction alertAction) {
                                    alertView.hide();
                                    Intent intent = new Intent(MainActivity.this, RegisterCompanyActivity.class);
                                    startActivity(intent);
                                }
                            }))
                            .addAction(new LemonAlertAction("加入公司", Color.RED, new LemonAlertActionDelegate() {
                                @Override
                                public void onClick(LemonAlertView alertView, LemonAlertInfo helloInfo, LemonAlertAction helloAction) {
                                    alertView.hide();
                                    Intent intent = new Intent(MainActivity.this, SearchCompanyActivity.class);
                                    startActivity(intent);
                                }
                            })).show(MainActivity.this);
                }
            });
        }
        tvUserName = (TextView) headerView.findViewById(R.id.tv_user_name);
        tvUserName.setText(User.getInstance().getRealName());
    }

    private void startQuizActivityWithTransition(Activity activity, View toolbar, int id) {
        final Pair[] pairs = TransitionHelper.createSafeTransitionParticipants(activity, false,
                new Pair<>(toolbar, activity.getString(R.string.transition_toolbar)));
        @SuppressWarnings("unchecked")
        ActivityOptionsCompat sceneTransitionAnimation = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, pairs);
        final Bundle transitionBundle = sceneTransitionAnimation.toBundle();
        Intent startIntent = new Intent(MainActivity.this, QuizActivity.class);
        startIntent.putExtra(Constants.Key.CATEGORY_ID, id);
        ActivityCompat.startActivity(activity,
                startIntent,
                transitionBundle);
    }


    public void syncAppVersion(final boolean isNoResponseForNoUpgrade) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mPresenter.fetchVersionName(MainActivity.this, isNoResponseForNoUpgrade);
            }
        }).start();
    }

    @Override
    public void setViewNotifyUpdate(Version version) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideProgressDialog();
                LemonAlert.getInformationAlert("提示", "发现新版本，请尽快下载更新！")
                        .addAction(new LemonAlertAction("知道啦", new LemonAlertActionDelegate() {
                            @Override
                            public void onClick(LemonAlertView alertView, LemonAlertInfo alertInfo, LemonAlertAction alertAction) {
                                alertView.hide();
                            }
                        }))
                        .addAction(new LemonAlertAction("确认下载", Color.RED, new LemonAlertActionDelegate() {
                            @Override
                            public void onClick(LemonAlertView alertView, LemonAlertInfo helloInfo, LemonAlertAction helloAction) {
                                alertView.hide();
                                mPresenter.downloadNewVersion(MainActivity.this);
                            }
                        })).show(MainActivity.this);
            }
        });
    }

    @Override
    public void setViewNoUpdate(final boolean isNoResponseForNoUpgrade) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideProgressDialog();
                if (!isNoResponseForNoUpgrade) {
                    LemonAlert.getInformationAlert("提示", "当前已经是最新版本了，不需要更新！")
                            .addAction(new LemonAlertAction("知道啦", new LemonAlertActionDelegate() {
                                @Override
                                public void onClick(LemonAlertView alertView, LemonAlertInfo alertInfo, LemonAlertAction alertAction) {
                                    alertView.hide();
                                }
                            })).show(MainActivity.this);
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_simple:
                setAdapterSimple();
                break;
            case R.id.action_standard:
                setAdapterStandard();
                break;
            case R.id.action_end_work:
                exit();
                break;
            case R.id.action_edit:

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void exit() {
        if (mDutyBean == null || mDutyBean.dutyId == null) {
            ToastUtils.show("没有查到上班信息");
            return;
        }
        WorkModel.getInstance().endWork(mDutyBean.dutyId).subscribe(new Subscriber<ResultBean<Object>>() {
            @Override
            public void onStart() {
                showProgressDialog("加载中...", true);
            }

            @Override
            public void onNext(ResultBean<Object> datas) {
                ToastUtils.show("下班成功");
                Intent loginStarter = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(loginStarter);
                SharePreferencesManager spm = new SharePreferencesManager(context);
                spm.writeBooleanSharedPreferences("isLogin", Boolean.FALSE);
                spm.writeStringSharedPreferences("password", null);
                finish();
            }

            @Override
            public void onCompleted() {
                hideProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                hideProgressDialog();
            }
        });
    }

    public void loadDutyInfo() {
        WorkModel.getInstance().loadWork().subscribe(new Subscriber<ResultBean<DutyLogBean>>() {
            @Override
            public void onStart() {
                showProgressDialog("加载中...", true);
            }

            @Override
            public void onNext(ResultBean<DutyLogBean> datas) {
                mDutyBean = datas.result.DutyLog;
                if (mDutyBean.gateNo != null) {
                    accebar.setCustomizeText(mDutyBean.gateName);
                }
                App.dutyId = mDutyBean.dutyId;
                App.gateName = mDutyBean.gateName;
                App.gateNo = mDutyBean.gateNo;
                switch (mDutyBean.ondutyClazz) {
                    case "1":
                        App.onTime = MessageFormat.format("{0}  早班", mDutyBean.createTime.substring(0, 10));
                        break;
                    case "2":
                        App.onTime = MessageFormat.format("{0}  中班", mDutyBean.createTime.substring(0, 10));
                        break;
                    default:
                        App.onTime = MessageFormat.format("{0}  晚班", mDutyBean.createTime.substring(0, 10));
                        break;
                }
                accebar.setPageCode(mDutyBean.dutyId);
            }

            @Override
            public void onCompleted() {
                hideProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideProgressDialog();
                ToastUtils.show("加载失败！");
            }
        });
    }
}
